<template>
	<div class="container add_edit">
		<el-form ref="ruleForm" label-width="150px">
			<div>
				<h3 class="margin_b_20">SKU</h3>
				<div>
					<el-form-item label="SKU">
						<el-switch @change="skuChange" v-model="sku" active-color="#ff6a6c" inactive-color="#dcdfe6">
						</el-switch>
						<div class="remark_txt">开启SKU商城价、原价、VIP价将取SKU最小价格</div>
					</el-form-item>
					<div v-if="sku" class="dflex_vertical_c" v-for="(item, i) in skuDatas" :key="i">
						<el-form-item label-width="150px">
							<el-checkbox v-model="item.enable" :disabled="i == 0" @change="skuEnable(item, i)">启用
							</el-checkbox>
						</el-form-item>
						<el-form-item label-width="60px" :label="'SKU' + (i + 1)">
							<el-input class="skuInput" v-model="item.name" :placeholder="'请输入SKU' + (i + 1)"
								maxlength="8" clearable :ref="'skuInput' + i" :disabled="!item.enable"
								@change="saveSkuInputValue(item.name, item, i)">
							</el-input>
						</el-form-item>
						<el-form-item label-width="20px" class="form_item">
							<div class="dflex_vertical_c dflex_wrap" v-if="i == 0">
								<div class="dflex_d_c dflex_c margin_r_10 margin_tb_5  sku_and_img pos_r"
									v-for="(tag, idx) in item.arrs" :key="idx">
									<uni-file-picker v-model="item.imgs[idx]" fileMediatype="image" returnType="object"
										:image-styles="imageStyle" @success="imgUpload"
										@delete="imgDelete(item.imgs, idx)" />
									<div style="font-size: 12px;" class="margin_t_10 ellipsis">{{ tag }}</div>
									<div class="el-icon-close crpr pos_a" @click="closeSkuTag(item, idx)"></div>
								</div>
								<el-input class="add_sku_input margin_tb_5" v-if="item.inputShow && i == 0"
									v-model="item.input" maxlength="30" :ref="'saveTagInput' + i"
									@keyup.enter.native="skuConfirmInputValue(item, i)"
									@blur="skuConfirmInputValue(item, i)"></el-input>
								<el-button v-else-if="i == 0" :disabled="item.name.trim() == ''"
									class="margin_tb_5 tag-btn" size="small" @click="skuInputFocus(item, i)">添加
								</el-button>
							</div>
							<div v-else class="dflex_vertical_c dflex_wrap">
								<el-tag type="info" class="margin_r_10 margin_tb_5" v-for="(tag, idx) in item.arrs"
									:key="idx" closable @close="closeSkuTag(item, idx)">
									{{ tag }}
								</el-tag>
								<el-input class="add_sku_input margin_tb_5" v-if="item.inputShow && i != 0"
									v-model="item.input" maxlength="30" :ref="'saveTagInput' + i"
									@keyup.enter.native="skuConfirmInputValue(item, i)"
									@blur="skuConfirmInputValue(item, i)"></el-input>
								<el-button v-else-if="i != 0" :disabled="item.name.trim() == ''"
									class="margin_tb_5 tag-btn" size="small" @click="skuInputFocus(item, i)">添加
								</el-button>
							</div>
						</el-form-item>
					</div>
					<el-form-item label-width="0">
						<el-table :data="tableSkuData" border v-if="sku && skuDatas && skuDatas.length > 0">
							<el-table-column align="center" width="120" :resizable="false" fixed="left">
								<template slot="header" slot-scope="scope">
									<div>图片</div>
									<div class="remark_txt margin_t_5">如果不选择</div>
									<div class="remark_txt">默认为商品首图</div>
								</template>
								<template slot-scope="scope">
									<uni-file-picker class="dflex_level_c" v-model="scope.row.imgObj"
										fileMediatype="image" returnType="object" :image-styles="imageStyle"
										@delete="imgDelete(scope.row)" />
								</template>
							</el-table-column>
							<el-table-column align="center" min-width="260">
								<template slot="header" slot-scope="scope">
									<div>商城价</div>
									<div class="dflex_level_c margin_t_10">
										<el-input class="batchInput margin_r_10" size="medium" type="number" :min="1"
											v-model="batchPrice" placeholder="商城价" clearable
											oninput="value = parseInt(value)"></el-input>
										<el-button class="batchBtn" size="medium" @click="batchEdit('price')">修改
										</el-button>
									</div>
								</template>
								<template slot-scope="scope">
									<el-input style="width:100%" type="number" v-model.number="scope.row.price" :min="1"
										@change="tableInputEdit('price', scope.row, '商城价')" placeholder="商城价"
										oninput="value = parseInt(value)">
									</el-input>
									<div class="remark_txt margin_t_0 left_just">单位为分，{{ scope.row.price || 0 }} 分 =
										{{ scope.row.price / 100 || 0 }} 元
									</div>
								</template>
							</el-table-column>
							<el-table-column align="center" min-width="260">
								<template slot="header" slot-scope="scope">
									<div>原价</div>
									<div class="dflex_level_c margin_t_10">
										<el-input class="batchInput margin_r_10" size="medium" type="number" :min="0"
											v-model="batchMarketPrice" placeholder="原价" clearable
											oninput="value = parseInt(value)"></el-input>
										<el-button class="batchBtn" size="medium" @click="batchEdit('market_price')">修改
										</el-button>
									</div>
								</template>
								<template slot-scope="scope">
									<el-input style="width:100%" type="number" :min="0"
										v-model.number="scope.row.market_price"
										@change="tableInputEdit('market_price', scope.row, '原价')" placeholder="原价"
										oninput="value = parseInt(value)">
									</el-input>
									<div class="remark_txt margin_t_0 left_just">单位为分，{{ scope.row.market_price || 0 }}
										分 = {{ scope.row.market_price / 100 || 0 }} 元</div>
								</template>
							</el-table-column>
							<el-table-column align="center" min-width="260" v-if="basicData.is_vip == '是'">
								<template slot="header" slot-scope="scope">
									<div>VIP价</div>
									<div class="dflex_level_c margin_t_10">
										<el-input class="batchInput margin_r_10" size="medium" type="number" :min="1"
											v-model="batchVipPrice" placeholder="VIP价" clearable
											oninput="value = parseInt(value)"></el-input>
										<el-button class="batchBtn" size="medium" @click="batchEdit('vip_price')">修改
										</el-button>
									</div>
								</template>
								<template slot-scope="scope">
									<el-input style="width:100%" type="number" :min="1"
										v-model.number="scope.row.vip_price"
										@change="tableInputEdit('vip_price', scope.row, 'VIP价')" placeholder="VIP价格"
										oninput="value = parseInt(value)">
									</el-input>
									<div class="remark_txt margin_t_0 left_just">
										单位为分，{{ scope.row.vip_price || 0 }} 分 = {{ scope.row.vip_price / 100 || 0 }} 元
									</div>
								</template>
							</el-table-column>
							<el-table-column align="center" min-width="260">
								<template slot="header" slot-scope="scope">
									<div>库存</div>
									<div class="dflex_level_c margin_t_10">
										<el-input class="batchInput margin_r_10" size="medium" type="number" :min="1"
											v-model.number="batchStockNum" placeholder="库存" clearable
											oninput="value = parseInt(value)"></el-input>
										<el-button class="batchBtn" size="medium" @click="batchEdit('stock_num')">修改
										</el-button>
									</div>
								</template>
								<template slot-scope="scope">
									<el-input style="width:100%" type="number" :min="1"
										v-model.number="scope.row.stock_num"
										@change="tableInputEdit('stock_num', scope.row, '库存')" placeholder="库存"
										oninput="value = parseInt(value)">
									</el-input>
									<div class="remark_txt margin_t_0 left_just">SKU库存数</div>
								</template>
							</el-table-column>
							<el-table-column :label="item.name" align="center"
								v-for="(item, i) in skuDatas.filter(x => x.arrs.length)" :key="i" min-width="260">
								<template slot-scope="scope">
									<el-input style="width:100%" v-model="scope.row[`sku${i + 1}_spec`]" clearable
										@change="saveSkuTableValue(item, scope.row, i)"></el-input>
									<div class="remark_txt margin_t_0 left_just"></div>
								</template>
							</el-table-column>
						</el-table>
					</el-form-item>
				</div>
			</div>
		</el-form>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				dataId: '',
				sku: false,
				skuDatas: [{
						enable: true,
						prev: '',
						name: '',
						input: '',
						inputShow: false,
						arrs: [],
						imgs: []
					},
					{
						enable: false,
						prev: '',
						name: '',
						input: '',
						inputShow: false,
						arrs: []
					},
					{
						enable: false,
						prev: '',
						name: '',
						input: '',
						inputShow: false,
						arrs: []
					},
					{
						enable: false,
						prev: '',
						name: '',
						input: '',
						inputShow: false,
						arrs: []
					}
				],
				imageStyle: {
					height: '80px',
					width: '80px',
					border: false
				},
				basicData: {},
				tableSkuData: [],
				tableSkuPrevData: [],
				batchPrice: null,
				batchMarketPrice: null,
				batchVipPrice: null,
				batchStockNum: null
			};
		},
		methods: {
			skuChange() {
				uni.$emit('sku', this.sku);

				if (this.sku || this.tableSkuData.length == 0) return;

				this.$confirm(`此操作将清除SKU数据, 是否继续?`, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					.then(() => {
						this.tableSkuData = [];
						this.skuDatas.forEach((x, idx) => {
							x.enable = false;
							if (idx == 0) {
								x.enable = true;
							}

							x.name = '';
							x.prev = '';
							x.arrs = [];
						});

						this.$message({
							type: 'success',
							message: '清除成功!'
						});
					})
					.catch(() => {
						this.sku = true;
						uni.$emit('sku', this.sku);
					});
			},
			skuEnable(item, idx) {
				if (item.enable) {
					this.$nextTick(() => {
						this.$refs['skuInput' + idx][0].focus();
					});
					return;
				}

				if (!(item.arrs && item.arrs.length > 0)) return;
				this.$confirm(`此操作将清除【${item.prev}】SKU数据, 是否继续?`, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					.then(() => {
						item.arrs = [];
						item.name = '';
						item.prev = '';

						this.$message({
							type: 'success',
							message: '清除成功!'
						});
						this.loadTableSkuData();
					})
					.catch(() => {
						item.enable = true;
					});

			},
			saveSkuInputValue(val, item, idx) {
				if (val) {
					// 判断是否已存在相同SKU名称
					if (this.skuDatas.find((x, i) => i !== idx && x.name == val)) {
						this.$message({
							type: 'warning',
							message: `SKU名称【${val}】已存在!`
						});
						item.name = '';
						return;
					}
					item.prev = val;
				}
			},
			skuInputFocus(item, idx) {
				item.inputShow = true;
				this.$nextTick(() => {
					this.$refs['saveTagInput' + idx][0].focus();
				});
			},
			skuConfirmInputValue(item, idx) {
				item.input = item.input.trim();
				if (item.input) {
					if (item.arrs.find(x => x == item.input)) {
						this.$message({
							message: 'SKU' + item.name + ' 已存在：[' + item.input + ']',
							type: 'warning'
						});

						item.inputShow = false;
						item.input = '';
						return;
					}

					item.arrs.push(item.input);
					if (item.imgs) item.imgs.push(null);
					this.loadTableSkuData();
				}
				item.inputShow = false;
				item.input = '';
			},
			closeSkuTag(item, idx) {
				item.arrs.splice(idx, 1);
				if (item.imgs) item.imgs.splice(idx, 1);

				this.loadTableSkuData();
			},
			loadTableSkuData() {
				// 存储上一次数据
				this.tableSkuPrevData = JSON.parse(JSON.stringify(this.tableSkuData));
				this.tableSkuData = [];

				let datas = this.skuDatas.filter(x => x.enable && x.arrs.length);

				if (!(datas && datas.length)) return;

				let obj = {};
				let prevImg = {};

				datas[0].imgs = datas[0].imgs || [];
				if (datas.length == 1) {
					datas[0].arrs.forEach((spec1, idx1) => {
						obj = this.tableSkuPrevData.find(d => d.sku1_spec == spec1) || {};
						prevImg = datas[0].imgs[idx1] || {
							url: this.basicData.img
						};
						if (!prevImg.url) {
							prevImg = null;
						}

						this.tableSkuData.push({
							imgObj: prevImg,
							price: obj.price || this.basicData.price,
							market_price: obj.market_price || this.basicData.market_price,
							vip_price: obj.vip_price || this.basicData.vip_price,
							stock_num: Boolean(this.dataId) ? obj.stock_num || 0 : obj.stock_num || this
								.basicData.stock_num || 0,

							sku1_name: datas[0].name,
							sku1_spec: spec1,
							sku1_idx: idx1
						});
					});
				}

				if (datas.length == 2)
					datas[0].arrs.forEach((spec1, idx1) => {
						prevImg = datas[0].imgs[idx1] || {
							url: this.basicData.img
						};
						if (!prevImg.url) {
							prevImg = null;
						}
						datas[1].arrs.forEach((spec2, idx2) => {
							obj = this.tableSkuPrevData.find(d => d.sku1_spec == spec1 && d.sku2_spec ==
								spec2) || {};
							this.tableSkuData.push({
								imgObj: prevImg,
								price: obj.price || this.basicData.price,
								market_price: obj.market_price || this.basicData.market_price,
								vip_price: obj.vip_price || this.basicData.vip_price,
								stock_num: Boolean(this.dataId) ? obj.stock_num || 0 : obj.stock_num ||
									this.basicData.stock_num || 0,

								sku1_name: datas[0].name,
								sku1_spec: spec1,
								sku1_idx: idx1,
								sku2_name: datas[1].name,
								sku2_spec: spec2,
								sku2_idx: idx2
							});
						});
					});
				if (datas.length == 3)
					datas[0].arrs.forEach((spec1, idx1) => {
						prevImg = datas[0].imgs[idx1] || {
							url: this.basicData.img
						};
						if (!prevImg.url) {
							prevImg = null;
						}
						datas[1].arrs.forEach((spec2, idx2) => {
							datas[2].arrs.forEach((spec3, idx3) => {
								obj = this.tableSkuPrevData.find(d => d.sku1_spec == spec1 && d
									.sku2_spec == spec2 && d.sku3_spec == spec3) || {};
								this.tableSkuData.push({
									imgObj: prevImg,
									price: obj.price || this.basicData.price,
									market_price: obj.market_price || this.basicData
										.market_price,
									vip_price: obj.vip_price || this.basicData.vip_price,
									stock_num: Boolean(this.dataId) ? obj.stock_num || 0 : obj
										.stock_num ||
										this.basicData
										.stock_num || 0,

									sku1_name: datas[0].name,
									sku1_spec: spec1,
									sku1_idx: idx1,
									sku2_name: datas[1].name,
									sku2_spec: spec2,
									sku2_idx: idx2,
									sku3_name: datas[2].name,
									sku3_spec: spec3,
									sku3_idx: idx3
								});
							});
						});
					});
				if (datas.length == 4)
					datas[0].arrs.forEach((spec1, idx1) => {
						prevImg = datas[0].imgs[idx1] || {
							url: this.basicData.img
						};
						if (!prevImg.url) {
							prevImg = null;
						}
						datas[1].arrs.forEach((spec2, idx2) => {
							datas[2].arrs.forEach((spec3, idx3) => {
								datas[3].arrs.forEach((spec4, idx4) => {
									obj = this.tableSkuPrevData.find(d => d.sku1_spec ==
										spec1 && d.sku2_spec == spec2 && d.sku3_spec ==
										spec3 && d.sku4_spec == spec4) || {};
									this.tableSkuData.push({
										imgObj: prevImg,
										price: obj.price || this.basicData.price,
										market_price: obj.market_price || this
											.basicData.market_price,
										vip_price: obj.vip_price || this.basicData
											.vip_price,
										stock_num: Boolean(this.dataId) ? obj
											.stock_num || 0 : obj.stock_num ||
											this.basicData
											.stock_num || 0,

										sku1_name: datas[0].name,
										sku1_spec: spec1,
										sku1_idx: idx1,
										sku2_name: datas[1].name,
										sku2_spec: spec2,
										sku2_idx: idx2,
										sku3_name: datas[2].name,
										sku3_spec: spec3,
										sku3_idx: idx3,
										sku4_name: datas[3].name,
										sku4_spec: spec4,
										sku4_idx: idx4
									});
								});
							});
						});
					});

				let goods_sku;
				this.tableSkuData.forEach(x => {
					goods_sku = '';
					if (x.sku1_name) {
						goods_sku += '1' + (x.sku1_idx + 1);
					}
					if (x.sku2_name) {
						goods_sku += '2' + (x.sku2_idx + 1);
					}
					if (x.sku3_name) {
						goods_sku += '3' + (x.sku3_idx + 1);
					}
					if (x.sku4_name) {
						goods_sku += '4' + (x.sku4_idx + 1);
					}

					x.goods_sku = goods_sku;
				})
			},
			imgUpload() {
				this.loadTableSkuData();
			},
			imgDelete(row, idx) {
				if (idx !== undefined) {
					row[idx] = null;
				} else {
					row.imgObj = null;
				}

				this.loadTableSkuData();
			},
			saveSkuTableValue(item, row, idx) {
				let spec = item.arrs[row[`sku${idx + 1}_idx`]];
				let val = row[`sku${idx + 1}_spec`];

				if (val.trim() == '') {
					this.$message({
						message: 'SKU不能为空',
						type: 'warning'
					});
					row[`sku${idx + 1}_spec`] = spec;
					return;
				}

				if (item.arrs.find(x => x == val)) {
					this.$message({
						message: 'SKU' + item.name + ' 已存在：[' + val + ']',
						type: 'warning'
					});
					row[`sku${idx + 1}_spec`] = spec;
					return;
				}

				item.arrs.push(val);
				item.arrs.splice(item.arrs.length - 1, 1);

				item.arrs[row[`sku${idx + 1}_idx`]] = val;
				this.loadTableSkuData();
			},
			setGoods(res) {
				this.basicData = res;

				this.loadTableSkuData();
			},
			submitData(callback) {
				let skus = [];
				let valid = true;
				if (this.sku) {
					let idx = this.skuDatas.findIndex(x => x.enable && !x.name.trim());
					if (idx != -1) {
						this.$message(`请添加 SKU${idx + 1} 名称`);
					} else {
						idx = this.skuDatas.findIndex(x => x.enable && x.arrs.length <= 0);
						if (idx != -1) {
							this.$message(`请添加 SKU${idx + 1} 数据`);
						}
					}

					if (idx != -1) valid = false;
				}

				if (typeof callback === 'function') {
					callback(this.skuDatas, this.tableSkuData, valid);
				}
			},
			getData(callback) {
				this.submitData(callback);
			},
			setData(res) {
				this.basicData = res.goods;
				if (res.skus && res.skus.length > 0) {
					this.sku = true;
					uni.$emit('sku', this.sku);
					if (res.goods.skus && res.goods.skus.length > 0) {
						res.goods.skus.forEach((x, i) => {
							if (i == 0) {
								if (!x.imgs || x.imgs.length != x.arrs.length) {
									x.imgs = new Array(x.arrs.length).fill(null);
								}
							}
						});

						this.skuDatas = res.goods.skus;

						res.skus.forEach(x => {
							x.imgObj = {
								url: x.img
							};
						});
						this.tableSkuData = res.skus;
						this.tableSkuPrevData = JSON.parse(JSON.stringify(this.tableSkuData));
					}
				}
			},
			batchEdit(res) {
				if (res == 'price') {
					if (this.batchPrice <= 0) {
						this.$message('请输入有效的商城价');
						return;
					}
				} else if (res == 'market_price') {
					if (!this.batchMarketPrice || this.batchMarketPrice < 0) {
						this.$message('请输入有效的原价');
						return;
					}
				} else if (res == 'vip_price') {
					if (this.batchVipPrice <= 0) {
						this.$message('请输入有效的VIP价');
						return;
					}
				} else if (res == 'stock_num') {
					if (this.batchStockNum <= 0) {
						this.$message('请输入有效的库存');
						return;
					}
				}
				this.tableSkuData.forEach(x => {
					if (res == 'price') {
						x.price = this.batchPrice;
					} else if (res == 'market_price') {
						x.market_price = this.batchMarketPrice;
					} else if (res == 'vip_price') {
						x.vip_price = this.batchVipPrice;
					} else if (res == 'stock_num') {
						x.stock_num = this.batchStockNum;
					}
				});
			},
			tableInputEdit(key, row, name) {
				if (['price', 'stock_num', 'vip_price'].includes(key)) {
					// 保存上一次的有效值
					let prev_val = event.target.dataset.val || 0;

					if (row[key] <= 0) {
						this.$message(`请输入有效的${name}`);
						row[key] = prev_val || this.basicData[key];
						return;
					}

					event.target.dataset.val = row[key];
				}

				if (key == 'market_price') {
					let prev_val = event.target.dataset.val || 0;

					if (!row.market_price || row.market_price < 0) {
						this.$message(`请输入有效的原价`);
						row.rebate_ratio = prev_val || this.basicData.rebate_ratio;
						return;
					}
					event.target.dataset.val = row.rebate_ratio;
				}
			}
		},
		created() {
			this.dataId = this.$route.query.id || '';
		}
	};
</script>

<style>
	>>>.icon-add {
		width: 30px;
	}

	>>>.icon-del-box {
		width: 16px;
		height: 16px;
	}

	>>>.icon-del {
		width: 10px;
	}

	>>>.file-picker__box-content:hover .icon-add {
		width: 40px;
	}

	>>>.el-table__row:hover>td {
		background-color: #fff !important;
	}

	>>>.el-table__row--striped:hover>td {
		background-color: #fff !important;
	}

	.sku_and_img {
		width: 120px;
		height: 120px;
		background-color: rgba(0, 0, 0, 0.1);
		padding: 10px;
		padding-bottom: 0px;
		border-radius: 10px;
	}

	.sku_and_img .el-icon-close {
		color: #909399;
		right: 6px;
		top: 10px;
	}

	.sku_and_img .el-icon-close:hover {
		color: #ff6a6c;
	}

	.form_item>>>.el-form-item__content {
		line-height: initial;
	}

	.form_item .ellipsis {
		width: 80px;
		text-align: center;
		color: #909399;
	}

	.skuInput {
		width: 200px;
	}

	.add_sku_input {
		width: 100px;
		height: 32px;
	}

	.add_sku_input>>>.el-input__inner {
		height: 100%;
	}

	.batchInput {
		height: 36px;
	}

	.batchInput>>>.el-input__inner {
		border-color: #dcdfe6;
		background-color: #fff;
	}

	.tag-btn:hover,
	.tag-btn:focus,
	.batchBtn:hover,
	.batchBtn:focus {
		color: #ff6a6c;
		border-color: #ff6a6c;
		background-color: #fff;
	}
</style>
